package com.sxf.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils {
	public static final int MAX_LIFE = 60 * 60 * 24 * 7;
	public static final String USER_ID = "COOKIE.USER.ID";
	public static final String USER_TEMP_ID = "COOKIE.USER.TEMP.ID";
	public static final String CART_ID = "cart";

	public static void addCookie(HttpServletRequest request,
			HttpServletResponse response, String key, String value) {
		try {
			addCookie(request, response, key, value, MAX_LIFE);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void addCookie(HttpServletRequest request,
			HttpServletResponse response, String key, String value, int max_age)
			throws UnsupportedEncodingException {
		value = URLEncoder.encode(value, "UTF-8");
		Cookie cookie = new Cookie(key, value);
		cookie.setMaxAge(max_age);
		cookie.setPath(request.getContextPath());

		// Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(request.getContextPath());
		response.addCookie(cookie);
	}

	public static void deleteCookie(HttpServletRequest request,
			HttpServletResponse response, String key) {
		Cookie cookie = new Cookie(key, "");
		cookie.setMaxAge(0);
		cookie.setPath(request.getContextPath());
		response.addCookie(cookie);
	}

	public static String findCookie(HttpServletRequest request,
			HttpServletResponse response, String key)
			throws UnsupportedEncodingException {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				Cookie cookie = cookies[i];
				if (key.equals(cookie.getName())) {
					return URLDecoder.decode(cookie.getValue(), "UTF-8");
				}
			}
		}
		return null;
	}
}
